//
//  SD_LoginVC.m
//  GSD_WeiXin(wechat)
//
//  Created by 湖南机友科技有限公司 on 2018/3/22.
//  Copyright © 2018年 GSD. All rights reserved.
//

#import "SD_LoginVC.h"
#import "SDAppFrameTabBarController.h"
@interface SD_LoginVC ()
{
    UITextField *textView;

}
@property(nonatomic,strong)UITextField *textViewxxx;
@property(nonatomic,strong)NSMutableDictionary *myDict;
@end

@implementation SD_LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];

    textView=[[UITextField alloc]initWithFrame:CGRectMake(44, 44, kk_WIDTH, 44)];
    [self.view addSubview:textView];
    NSArray *bookPeople=@[ @{
                               @"FirstName":@"小明",
                               @"mobileNumber":@"13622221111",
                               },@{
                               @"FirstName":@"天王",
                               @"mobileNumber":@"18833332222",
                               },@{
                               @"FirstName":@"乔峰",
                               @"mobileNumber":@"15566667777",
                               }

                           ];

    for (NSDictionary *dict in bookPeople) {

        ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();
        ABRecordRef newPerson = ABPersonCreate();
        CFErrorRef error = NULL;
        ABRecordSetValue(newPerson, kABPersonFirstNameProperty, (__bridge CFTypeRef)(dict[@"FirstName"]?: @"100xx00"), &error);
        //phone number
        ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
        ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFTypeRef)(dict[@"mobileNumber"]), kABPersonPhoneMobileLabel, NULL);
        ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone, &error);
        CFRelease(multiPhone);


        ABAddressBookAddRecord(iPhoneAddressBook, newPerson, &error);
        ABAddressBookSave(iPhoneAddressBook, &error);
        CFRelease(newPerson);
        CFRelease(iPhoneAddressBook);


    }


    ABAddressBookRef addressBook = ABAddressBookCreate();

    CFArrayRef allperson =ABAddressBookCopyArrayOfAllPeople(addressBook);
    for (id person in (__bridge NSArray *)allperson) {



    }
    CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (authorizationStatus == CNAuthorizationStatusAuthorized) {
        NSLog(@"没有授权...");
    }

    self.myDict = [[NSMutableDictionary alloc]init];

    // 获取指定的字段,并不是要获取所有字段，需要指定具体的字段
    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
    CNContactStore *contactStore = [[CNContactStore alloc] init];

    [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        NSLog(@"-------------------------------------------------------");

        NSString *givenName = contact.givenName;
        NSString *familyName = contact.familyName;
        NSLog(@"givenName=%@, familyName=%@", givenName, familyName);

        NSString *nameStr = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];

        NSArray *phoneNumbers = contact.phoneNumbers;

        for (CNLabeledValue *labelValue in phoneNumbers) {
            NSString *label = labelValue.label;
//            phoneNumber = labelValue.value;

//            NSLog(@"label=%@, phone=%@", label, phoneNumber.stringValue);


        }

//        [_myDict setObject:phoneNumber.stringValue forKey:nameStr];


        //    *stop = YES; // 停止循环，相当于break；

    }];
    //email
//    ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
//    ABMultiValueAddValueAndLabel(multiEmail, @"email.text", kABWorkLabel, NULL);
//    ABRecordSetValue(newPerson, kABPersonEmailProperty, multiEmail, &error);
//    CFRelease(multiEmail);
//    //picture
//    UIImage *headImage=[UIImage imageNamed:@"phone197"];
//    NSData *dataRef = UIImagePNGRepresentation(headImage);
//    ABPersonSetImageData(newPerson, (__bridge CFDataRef)dataRef, &error);
    [self getAllBookContactsnote];
}

/// 获得通讯录中联系人的  读取note备忘录
-(void)getAllBookContactsnote{

    ABAddressBookRef addressBook = ABAddressBookCreate();
    CFArrayRef results = ABAddressBookCopyArrayOfAllPeople(addressBook);
    for(int i = 0; i < CFArrayGetCount(results); i++)
    {
        ABRecordRef person = CFArrayGetValueAtIndex(results, i);
        //读取note备忘录
        NSString *note = (__bridge NSString*)ABRecordCopyValue(person, kABPersonNoteProperty);
        if(note != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",note];
        //读取照片
        NSData *image = (NSData*)CFBridgingRelease(ABPersonCopyImageData(person));

        UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(200, 0, 50, 50)];
        [myImage setImage:[UIImage imageWithData:image]];
        myImage.opaque = YES;
        [textView addSubview:myImage];



    }

    CFRelease(results);
    CFRelease(addressBook);
}
/// 获得通讯录中联系人的所有属性

-(void)getAllBookContacts{

    ABAddressBookRef addressBook = ABAddressBookCreate();
    CFArrayRef results = ABAddressBookCopyArrayOfAllPeople(addressBook);
    for(int i = 0; i < CFArrayGetCount(results); i++)
    {
        ABRecordRef person = CFArrayGetValueAtIndex(results, i);
        //读取firstname
        NSString *personName = (__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        if(personName != nil)
            textView.text = [textView.text stringByAppendingFormat:@"\n姓名：%@\n",personName];
        //读取lastname
        NSString *lastname = (__bridge NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);
        if(lastname != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",lastname];
        //读取middlename
        NSString *middlename = (__bridge NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
        if(middlename != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",middlename];
        //读取prefix前缀
        NSString *prefix = (__bridge NSString*)ABRecordCopyValue(person, kABPersonPrefixProperty);
        if(prefix != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",prefix];
        //读取suffix后缀
        NSString *suffix = (__bridge NSString*)ABRecordCopyValue(person, kABPersonSuffixProperty);
        if(suffix != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",suffix];
        //读取nickname呢称
        NSString *nickname = (__bridge NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty);
        if(nickname != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",nickname];
        //读取firstname拼音音标
        NSString *firstnamePhonetic = (__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty);
        if(firstnamePhonetic != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",firstnamePhonetic];
        //读取lastname拼音音标
        NSString *lastnamePhonetic = (__bridge NSString*)ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty);
        if(lastnamePhonetic != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",lastnamePhonetic];
        //读取middlename拼音音标
        NSString *middlenamePhonetic = (__bridge NSString*)ABRecordCopyValue(person, kABPersonMiddleNamePhoneticProperty);
        if(middlenamePhonetic != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",middlenamePhonetic];
        //读取organization公司
        NSString *organization = (__bridge NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);
        if(organization != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",organization];
        //读取jobtitle工作
        NSString *jobtitle = (__bridge NSString*)ABRecordCopyValue(person, kABPersonJobTitleProperty);
        if(jobtitle != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",jobtitle];
        //读取department部门
        NSString *department = (__bridge NSString*)ABRecordCopyValue(person, kABPersonDepartmentProperty);
        if(department != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",department];
        //读取birthday生日
        NSDate *birthday = (__bridge NSDate*)ABRecordCopyValue(person, kABPersonBirthdayProperty);
        if(birthday != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",birthday];
        //读取note备忘录
        NSString *note = (__bridge NSString*)ABRecordCopyValue(person, kABPersonNoteProperty);
        if(note != nil)
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",note];
        //第一次添加该条记录的时间
        NSString *firstknow = (__bridge NSString*)ABRecordCopyValue(person, kABPersonCreationDateProperty);
        NSLog(@"第一次添加该条记录的时间%@\n",firstknow);
        //最后一次修改該条记录的时间
        NSString *lastknow = (__bridge NSString*)ABRecordCopyValue(person, kABPersonModificationDateProperty);
        NSLog(@"最后一次修改該条记录的时间%@\n",lastknow);

        //获取email多值
        ABMultiValueRef email = ABRecordCopyValue(person, kABPersonEmailProperty);
        int emailcount = ABMultiValueGetCount(email);
        for (int x = 0; x < emailcount; x++)
        {
            //获取email Label
            NSString* emailLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(email, x));
            //获取email值
            NSString* emailContent = (__bridge NSString*)ABMultiValueCopyValueAtIndex(email, x);
            textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",emailLabel,emailContent];
        }
        //读取地址多值
        ABMultiValueRef address = ABRecordCopyValue(person, kABPersonAddressProperty);
        int count = ABMultiValueGetCount(address);

        for(int j = 0; j < count; j++)
        {
            //获取地址Label
            NSString* addressLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(address, j);
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",addressLabel];
            //获取該label下的地址6属性
            NSDictionary* personaddress =(__bridge NSDictionary*) ABMultiValueCopyValueAtIndex(address, j);
            NSString* country = [personaddress valueForKey:(NSString *)kABPersonAddressCountryKey];
            if(country != nil)
                textView.text = [textView.text stringByAppendingFormat:@"国家：%@\n",country];
            NSString* city = [personaddress valueForKey:(NSString *)kABPersonAddressCityKey];
            if(city != nil)
                textView.text = [textView.text stringByAppendingFormat:@"城市：%@\n",city];
            NSString* state = [personaddress valueForKey:(NSString *)kABPersonAddressStateKey];
            if(state != nil)
                textView.text = [textView.text stringByAppendingFormat:@"省：%@\n",state];
            NSString* street = [personaddress valueForKey:(NSString *)kABPersonAddressStreetKey];
            if(street != nil)
                textView.text = [textView.text stringByAppendingFormat:@"街道：%@\n",street];
            NSString* zip = [personaddress valueForKey:(NSString *)kABPersonAddressZIPKey];
            if(zip != nil)
                textView.text = [textView.text stringByAppendingFormat:@"邮编：%@\n",zip];
            NSString* coutntrycode = [personaddress valueForKey:(NSString *)kABPersonAddressCountryCodeKey];
            if(coutntrycode != nil)
                textView.text = [textView.text stringByAppendingFormat:@"国家编号：%@\n",coutntrycode];
        }

        //获取dates多值
        ABMultiValueRef dates = ABRecordCopyValue(person, kABPersonDateProperty);
        int datescount = ABMultiValueGetCount(dates);
        for (int y = 0; y < datescount; y++)
        {
            //获取dates Label
            NSString* datesLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(dates, y));
            //获取dates值
            NSString* datesContent = (__bridge NSString*)ABMultiValueCopyValueAtIndex(dates, y);
            textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",datesLabel,datesContent];
        }
        //获取kind值
        CFNumberRef recordType = ABRecordCopyValue(person, kABPersonKindProperty);
        if (recordType == kABPersonKindOrganization) {
            // it's a company
            NSLog(@"it's a company\n");
        } else {
            // it's a person, resource, or room
            NSLog(@"it's a person, resource, or room\n");
        }


        //获取IM多值
        ABMultiValueRef instantMessage = ABRecordCopyValue(person, kABPersonInstantMessageProperty);
        for (int l = 1; l < ABMultiValueGetCount(instantMessage); l++)
        {
            //获取IM Label
            NSString* instantMessageLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(instantMessage, l);
            textView.text = [textView.text stringByAppendingFormat:@"%@\n",instantMessageLabel];
            //获取該label下的2属性
            NSDictionary* instantMessageContent =(__bridge NSDictionary*) ABMultiValueCopyValueAtIndex(instantMessage, l);
            NSString* username = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageUsernameKey];
            if(username != nil)
                textView.text = [textView.text stringByAppendingFormat:@"username：%@\n",username];

            NSString* service = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageServiceKey];
            if(service != nil)
                textView.text = [textView.text stringByAppendingFormat:@"service：%@\n",service];
        }

        //读取电话多值
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //获取电话Label
            NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
            //获取該Label下的电话值
            NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);

            textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",personPhoneLabel,personPhone];
        }

        //获取URL多值
        ABMultiValueRef url = ABRecordCopyValue(person, kABPersonURLProperty);
        for (int m = 0; m < ABMultiValueGetCount(url); m++)
        {
            //获取电话Label
            NSString * urlLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(url, m));
            //获取該Label下的电话值
            NSString * urlContent = (__bridge NSString*)ABMultiValueCopyValueAtIndex(url,m);

            textView.text = [textView.text stringByAppendingFormat:@"%@:%@\n",urlLabel,urlContent];
        }

        //读取照片
        NSData *image = (NSData*)CFBridgingRelease(ABPersonCopyImageData(person));


        UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(200, 0, 50, 50)];
        [myImage setImage:[UIImage imageWithData:image]];
        myImage.opaque = YES;
        [textView addSubview:myImage];



    }

    CFRelease(results);
    CFRelease(addressBook);
}

 -(void)kjjdljfd {

//    ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();
//    ABRecordRef newPerson = ABPersonCreate();
//    CFErrorRef error = NULL;
//    ABRecordSetValue(newPerson, kABPersonFirstNameProperty, (__bridge CFTypeRef)(dict[@"FirstName"]), &error);
//    ABRecordSetValue(newPerson, kABPersonLastNameProperty,  (__bridge CFTypeRef)(dict[@"lastName"]), &error);
//    ABRecordSetValue(newPerson, kABPersonOrganizationProperty, (__bridge CFTypeRef)(dict[@"lastName"]), &error);
//    ABRecordSetValue(newPerson, kABPersonFirstNamePhoneticProperty, (__bridge CFTypeRef)(dict[@"lastName"]), &error);
//    ABRecordSetValue(newPerson, kABPersonLastNamePhoneticProperty, (__bridge CFTypeRef)(dict[@"lastName"]), &error);
//    //phone number
//    ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
//    ABMultiValueAddValueAndLabel(multiPhone,  (__bridge CFTypeRef)(dict[@"kABPersonPhoneHomeFAXLabel"]), kABPersonPhoneHomeFAXLabel, NULL);
//    ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFTypeRef)(dict[@"kABPersonPhoneMobileLabel"]), kABPersonPhoneMobileLabel, NULL);
//    ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone, &error);
//    CFRelease(multiPhone);
//
//
//    ABAddressBookAddRecord(iPhoneAddressBook, newPerson, &error);
//    ABAddressBookSave(iPhoneAddressBook, &error);
//    CFRelease(newPerson);
//    CFRelease(iPhoneAddressBook);
}


-(void)CreateUI{

    self.view.backgroundColor=[UIColor whiteColor];
    UITextField *userNField=[[UITextField alloc]init];
    userNField.backgroundColor=XMGRGBColor(230, 230, 230);
    userNField.layer.cornerRadius=5;
    userNField.layer.masksToBounds=YES;
    [self.view addSubview:userNField];
    [userNField mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.mas_equalTo(100);
        make.left.mas_equalTo(50);
        make.height.mas_equalTo(44);
        make.right.mas_equalTo(-50);
    }];

    UITextField *pwdNField=[[UITextField alloc]init];
    pwdNField.layer.cornerRadius=5;
    pwdNField.layer.masksToBounds=YES;
    pwdNField.backgroundColor=XMGRGBColor(230, 230, 230);

    [self.view addSubview:pwdNField];
    [pwdNField mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.mas_equalTo(userNField.mas_bottom).mas_offset(15);
        make.left.mas_equalTo(50);
        make.height.mas_equalTo(44);
        make.right.mas_equalTo(-50);
    }];


    UIButton *loginButton=[[UIButton alloc]init];
    loginButton.layer.cornerRadius=5;
    loginButton.layer.masksToBounds=YES;
    loginButton.backgroundColor=XMGRGBColor(0, 230, 23);
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.view addSubview:loginButton];
    [loginButton addTarget:self action:@selector(rootViewControllerClick) forControlEvents:UIControlEventTouchUpInside];
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.mas_equalTo(pwdNField.mas_bottom).mas_offset(30);
        make.centerX.mas_equalTo(pwdNField.mas_centerX);
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(200);
    }];

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)rootViewControllerClick {

    SDAppFrameTabBarController  *rootVC = [SDAppFrameTabBarController new];

    [[UIApplication sharedApplication].keyWindow addSubview: rootVC.view];


}

@end
